package com.xywl.escort.view.user;

import com.xywl.escort.bean.BaseReq;
import com.xywl.escort.bean.BaseResp;
import com.xywl.escort.bean.UpdateUserInfoReq;
import com.xywl.escort.bean.UploadImageResp;
import com.xywl.escort.bean.UserAutoInfoResp;
import com.xywl.escort.bean.UserInfoResp;
import com.xywl.escort.net.BaseSubscriber;
import com.xywl.escort.net.ExceptionHandle;
import com.xywl.escort.net.api.service.ApiServer;
import com.xywl.escort.utils.FileUtil;
import com.xywl.escort.utils.RxUtil;

import org.reactivestreams.Publisher;

import java.io.File;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by 32422 on 2017/10/25.
 */

public class UserInfoPresenter implements UserInfoContract.Presenter {
    private UserInfoContract.View mView;
    private ApiServer mApiServer;
    private String headImg = "";

    @Inject
    UserInfoPresenter(ApiServer apiServer) {
        mApiServer = apiServer;
    }

    @Override
    public void subscribe() {

    }

    @Override
    public void unSubscribe() {
        mView = null;
    }

    @Override
    public void takeView(UserInfoContract.View view) {
        this.mView = view;
    }

    @Override
    public void findUserInfo(String userId) {
        BaseReq req = new BaseReq();
        req.id = userId;
        mApiServer.findUserInfoById(req)
                .compose(RxUtil.<UserInfoResp>applySchedulers(RxUtil.IO_ON_UI_TRANSFORMER_BACK_PRESSURE))
                .compose(mView.<UserInfoResp>bindToLife())
                .subscribe(new BaseSubscriber<UserInfoResp>() {
                    @Override
                    protected void hideDialog() {

                    }

                    @Override
                    protected void showDialog() {

                    }

                    @Override
                    public void onError(ExceptionHandle.ResponseThrowable e) {
                        mView.findUserInfoFailure("获取用户信息失败，请稍后重试");
                    }

                    @Override
                    public void onNext(UserInfoResp resp) {
                        if (null != resp) {
                            if (resp.isOk() && null != resp.data) {
                                mView.findUserInfoSuccess(resp.data);
                            } else {
                                mView.findUserInfoFailure(resp.msg);
                            }
                        } else {
                            mView.findUserInfoFailure("获取用户信息失败，请稍后重试");
                        }
                    }
                });
    }

    @Override
    public void findUserAutoInfo(String userId) {
        BaseReq req = new BaseReq();
        req.userId = userId;
        mApiServer.findUserAutoByUserId(req)
                .compose(RxUtil.<UserAutoInfoResp>applySchedulers(RxUtil.IO_ON_UI_TRANSFORMER_BACK_PRESSURE))
                .compose(mView.<UserAutoInfoResp>bindToLife())
                .subscribe(new BaseSubscriber<UserAutoInfoResp>() {
                    @Override
                    protected void hideDialog() {

                    }

                    @Override
                    protected void showDialog() {

                    }

                    @Override
                    public void onError(ExceptionHandle.ResponseThrowable e) {
                        mView.findUserAutoInfoFailure();
                    }

                    @Override
                    public void onNext(UserAutoInfoResp resp) {
                        if (null != resp && null != resp.data && resp.isOk()) {
                            mView.findUserAutoInfoSuccess(resp.data);
                        } else {
                            mView.findUserAutoInfoFailure();
                        }
                    }
                });
    }

    @Override
    public void updateUserInfo(String nickname, String userId) {
        UpdateUserInfoReq req = new UpdateUserInfoReq();
        req.nickname = nickname;
        req.id = userId;
        mApiServer.updateUserInfo(req)
                .compose(RxUtil.<BaseResp>applySchedulers(RxUtil.IO_ON_UI_TRANSFORMER_BACK_PRESSURE))
                .compose(mView.<BaseResp>bindToLife())
                .subscribe(new BaseSubscriber<BaseResp>() {
                    @Override
                    protected void hideDialog() {

                    }

                    @Override
                    protected void showDialog() {

                    }

                    @Override
                    public void onError(ExceptionHandle.ResponseThrowable e) {
                        mView.updateUserInfoFailure("修改个人信息失败");
                    }

                    @Override
                    public void onNext(BaseResp resp) {
                        if (null != resp) {
                            if (resp.isOk()) {
                                mView.updateNicknameSuccess(resp);
                            } else {
                                mView.updateUserInfoFailure(resp.msg);
                            }
                        } else {
                            mView.updateUserInfoFailure("修改个人信息失败");
                        }
                    }
                });
    }

    @Override
    public void updateUserInfo(final String path, final String nickname, final String userId) {
        final File file = new File(path);
        if (file.exists()) {
            if (FileUtil.isImageFormat(file)) {
                RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
                mApiServer.uploadImage(part)
                        .compose(RxUtil.<UploadImageResp>applySchedulers(RxUtil.IO_ON_UI_TRANSFORMER_BACK_PRESSURE))
                        .compose(mView.<UploadImageResp>bindToLife())
                        .filter(new Predicate<UploadImageResp>() {
                            @Override
                            public boolean test(UploadImageResp resp) {
                                return null != resp && null != resp.data && resp.isOk();
                            }
                        })
                        .observeOn(Schedulers.io())
                        .map(new Function<UploadImageResp, UpdateUserInfoReq>() {
                            @Override
                            public UpdateUserInfoReq apply(UploadImageResp resp) {
                                UpdateUserInfoReq req = new UpdateUserInfoReq();
                                headImg = resp.data.url;
                                req.headImg = headImg;
                                req.id = userId;
                                return req;
                            }
                        })
                        .flatMap(new Function<UpdateUserInfoReq, Publisher<BaseResp>>() {
                            @Override
                            public Publisher<BaseResp> apply(UpdateUserInfoReq req) {
                                return mApiServer.updateUserInfo(req);
                            }
                        })
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseSubscriber<BaseResp>() {
                            @Override
                            protected void hideDialog() {

                            }

                            @Override
                            protected void showDialog() {

                            }

                            @Override
                            public void onError(ExceptionHandle.ResponseThrowable e) {
                                mView.updateUserInfoFailure("修改个人信息失败");
                            }

                            @Override
                            public void onNext(BaseResp resp) {
                                if (null != resp) {
                                    if (resp.isOk()) {
                                        mView.updateAvatarSuccess(resp, headImg);
                                    } else {
                                        mView.updateUserInfoFailure(resp.msg);
                                    }
                                } else {
                                    mView.updateUserInfoFailure("修改个人信息失败");
                                }
                            }
                        });
            }
        }
    }
}
